package severlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import dao.PassageMapper;
import dao.UserMapper;
import model.Passage;
import model.User;
import util.SqlSessionUtil;



/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/MainServlet")
/**
* @author 听风寂  ，林舒馨
* @date 2020/1/8
* @ClassName MainServlet
*/
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String search = request.getParameter("search");
		String reading = request.getParameter("reading");
		System.out.println(reading);		
		//这个能顺利打印出用户名
		System.out.println(request.getSession().getAttribute("user"));
		String userName =request.getSession().getAttribute("user").toString();
		System.out.println(search);
		//保存session id 把search返回值保存到session当前会话中，名称为search，只要当前会话不过期，任何地方都可以访到
		request.getSession().setAttribute("search", search);
		request.getSession().setAttribute("reading", reading);

		//写入个人信息
		//解决后端向前端传数据中文乱码问题
		 response.setCharacterEncoding("UTF-8");
		JSONObject object=new JSONObject();
		PrintWriter out = response.getWriter();  
		SqlSession s=SqlSessionUtil.getSqlSession();
		PassageMapper paGet = s.getMapper(PassageMapper.class);
		//首页随机推荐的3篇文章
		List<Passage> lisThree = paGet.selectThree();
		//个人点击数的前四的4篇文章
		List<Passage> lisFour = paGet.selectFour(userName); 
		UserMapper userGet = s.getMapper(UserMapper.class);
		User user = userGet.selectUser(userName);
		object.put("passage", lisThree);
		object.put("artcle", lisFour);
		object.put("user", user);
		String jsonStr = JSON.toJSONString(object);
		out.print(jsonStr);
		out.close();	
				
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
